import React from 'react';
import { Form, Row, Col, Input, Select, InputNumber, Upload, Button, message, Table } from 'antd';
import { DEFAULT_PAGE_SIZE, PREFIX } from '../../../../utils/constants';
import styles from '../../../common.less';
import ProductMaturityModal from './ProductMaturityModal';

const Option = Select.Option;

@Form.create()
export default class ProductMaturityPanel extends React.Component {
  constructor() {
    super();
    const userGrades = [];
    ['A', 'B', 'C', 'D', 'E', 'F'].forEach((item) => {
      ['1', '2', '3', '4', '5'].forEach((a) => {
        userGrades.push(`${item}${a}`);
      });
    });
    this.state = {
      userGrades,
      current: {},
      modalVisible: false,
    };
  }
  handleToAddOrUpdate = (record = {}) => {
    this.setState({
      current: record,
      modalVisible: true,
    });
  };
  handleUpdate = (field, value, record) => {
    const { dispatch, form: { setFieldsValue } } = this.props;
    const realField = field.slice(0, (0 - `$${record.id}`.length));
    const nextRecord = { ...record };
    nextRecord[realField] = value;
    dispatch({
      type: 'product/updateProductMaturity',
      payload: {
        params: nextRecord,
        reset: () => {
          const changeObj = {};
          changeObj[field] = record[realField];
          setTimeout(() => { // 确保排在form的默认设置逻辑之后。。
            setFieldsValue(changeObj);
          }, 10);
        },
      },
    });
  };
  handleDelete = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'product/deleteProductMaturity',
      payload: {
        params: record,
      },
    });
  };
  render() {
    const {
      dispatch,
      loading,
      productInfo,
      productMaturityData,
      form: { getFieldDecorator },
    } = this.props;
    const { userGrades, current, modalVisible } = this.state;
    const columns = [
      {
        title: '评级',
        dataIndex: 'riskRating',
        key: 'riskRating',
        render: (text, record) => {
          const field = `riskRating$${record.id}`;
          return getFieldDecorator(field, {
            initialValue: text,
          })(
            <Select
              style={{ width: '100%' }}
              size="small"
              showSearch
              optionFilterProp="children"
              onChange={(value) => {
                if (value !== text) {
                  this.handleUpdate(field, value, record);
                }
              }}
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
              {
                userGrades.map((item, index) => {
                  return <Option key={index} value={item}>{item}</Option>;
                })
              }
            </Select>
          );
        },
      },
      {
        title: '最小金额',
        dataIndex: 'minAmount',
        key: 'minAmount',
        render: (text, record) => {
          const field = `minAmount$${record.id}`;
          return getFieldDecorator(field, {
            initialValue: text,
          })(
            <InputNumber
              style={{ width: '100%' }}
              size="small"
              min={0}
              onBlur={(e) => {
                const value = e.target.value;
                if (value !== text) {
                  this.handleUpdate(field, value, record);
                }
              }}
            />
          );
        },
      },
      {
        title: '最大金额',
        dataIndex: 'maxAmount',
        key: 'maxAmount',
        render: (text, record) => {
          const field = `maxAmount$${record.id}`;
          return getFieldDecorator(field, {
            initialValue: text,
          })(
            <InputNumber
              style={{ width: '100%' }}
              size="small"
              min={0}
              onBlur={(e) => {
                const value = e.target.value;
                if (value !== text) {
                  this.handleUpdate(field, value, record);
                }
              }}
            />
          );
        },
      },
      {
        title: '期限',
        dataIndex: 'maturity',
        key: 'maturity',
        render: (text, record) => {
          const field = `maturity$${record.id}`;
          return getFieldDecorator(field, {
            initialValue: text,
          })(
            <Input
              size="small"
              onBlur={(e) => {
                const value = e.target.value;
                if (value !== text) {
                  this.handleUpdate(field, value, record);
                }
              }}
            />
          );
        },
      },
      {
        title: '操作',
        render: (text, record) => {
          return (
            <span className={styles.operation}>
              <a onClick={() => this.handleToAddOrUpdate(record)}>修改</a>
              <a style={{ color: 'red' }} onClick={() => this.handleDelete(record)}>删除</a>
            </span>
          );
        },
      },
    ];
    const productMaturityModalProps = {
      dispatch,
      loading,
      visible: modalVisible,
      productInfo,
      current,
      userGrades,
      onCancel: () => {
        this.setState({
          current: {},
          modalVisible: false,
        });
      },
    };
    return (
      <div>
        <Row style={{ marginBottom: 8 }}>
          <Col span={16}>
            <Upload
              action={`${PREFIX}/upload?productId=${productInfo.id}&excelType=PRODUCT_MATURITY`}
              onChange={(info) => {
                if (info.file.status === 'done') {
                  dispatch({
                    type: 'product/fetchProductMaturity',
                    payload: {
                      productId: productInfo.id,
                    },
                  });
                  message.success(`${info.file.name} 导入成功！`);
                } else if (info.file.status === 'error') {
                  const errMsg = info.file.response.errMsg;
                  message.error(`导入失败${errMsg ? `：${errMsg}` : '！'}`);
                }
              }}
              showUploadList={false}
            >
              <Button icon="upload">导入配置</Button>
            </Upload>
            <span style={{ marginLeft: 20 }}>导入配置会覆盖已有数据</span>
          </Col>
          <Col span={8}>
            <div className={styles.btnGroup}>
              <Button type="primary" onClick={() => this.handleToAddOrUpdate()}>添加</Button>
            </div>
          </Col>
        </Row>
        <Table
          size="small"
          columns={columns}
          dataSource={productMaturityData}
          loading={loading}
          rowKey={record => record.id}
          pagination={{
            pageSize: DEFAULT_PAGE_SIZE,
          }}
          bordered
        />
        <ProductMaturityModal {...productMaturityModalProps} />
      </div>
    );
  }
}
